﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace HSIA
{

    public class DataOrder
    {
        public delegate bool SendOrder(string sIP, byte[] byteHex);
        public SendOrder netSend;

        DatabaseObject dbo;

        public IntPtr frmHandle;

        public Dictionary<string, MyReceiver> htRecriver = new Dictionary<string, MyReceiver>();

        public DataTable dtOrderType, dtDeviceType;
        public DataTable dtReceiver;
        private DataTable dtRecedRecord;

        public string sGatherNo = "";
        public bool blDataFromCall = false;

        string sLastHead = "";
        int iCurLen = 0;

        public DataOrder(DatabaseObject vdbo)
        {
            dbo = vdbo;
            InitOrder();
            InitdtRecedRecord();
        }

        private void InitOrder()
        {
            dtOrderType = new DataTable("Order");
            dtOrderType.Columns.Add("Head", Type.GetType("System.String"));
            dtOrderType.Columns.Add("Name", Type.GetType("System.String"));
            dtOrderType.Columns.Add("ValueType", Type.GetType("System.Int32"));
            dtOrderType.Columns.Add("ValueLen", Type.GetType("System.Int32"));
            dtOrderType.Columns.Add("EndTag", Type.GetType("System.Int32"));

            dtOrderType.PrimaryKey = new DataColumn[] { dtOrderType.Columns["Name"] };

            dtOrderType.LoadDataRow(new object[] { "6855", "采集数据", 1, 2, 0x0D }, true);
            dtOrderType.LoadDataRow(new object[] { "6866", "补发数据", 1, 0, 0x0D }, true);
            dtOrderType.LoadDataRow(new object[] { "6877", "查询编号", 1, 0, 0x0D }, true);
            //dtOrder.LoadDataRow(new object[] { "6888", "设置时钟", 3, 1, 0x0D }, true);
            //dtOrder.LoadDataRow(new object[] { "6899", "历史数据", 0, 0, 0x0D }, true);
            //dtOrder.LoadDataRow(new object[] { "68AA", "设置周期", 2, 2, 0x0D }, true);
            //dtOrder.LoadDataRow(new object[] { "68BB", "重启设备", 0, 0, 0x0D }, true);
            //dtOrder.LoadDataRow(new object[] { "68CC", "获取参数", 0, 0, 0x0D }, true);
            //dtOrder.LoadDataRow(new object[] { "68DD", "设置阀值", 2, 2, 0x0D }, true);

            dtOrderType.LoadDataRow(new object[] { "6A1F", "注册传感器", 1, 1, 0x0D }, true);
            dtOrderType.LoadDataRow(new object[] { "6A20", "设置时钟", 1, 1, 0x0D }, true);
            dtOrderType.LoadDataRow(new object[] { "6A21", "读取参数", 1, 1, 0x0D }, true);
            dtOrderType.LoadDataRow(new object[] { "6A22", "读取射频", 1, 1, 0x0D }, true);
            dtOrderType.LoadDataRow(new object[] { "6A23", "设置周期", 1, 1, 0x0D }, true);
            dtOrderType.LoadDataRow(new object[] { "6A24", "设置阀值", 1, 1, 0x0D }, true);
            dtOrderType.LoadDataRow(new object[] { "6A25", "重启设备", 1, 0, 0x0D }, true);

            dtDeviceType = new DataTable("Order");
            dtDeviceType.Columns.Add("Version_Code", Type.GetType("System.String"));
            dtDeviceType.Columns.Add("Version_Type", Type.GetType("System.Int32"));
            dtDeviceType.Columns.Add("Version_Name", Type.GetType("System.String"));

            dtDeviceType.PrimaryKey = new DataColumn[] { dtDeviceType.Columns["Version_Type"] };

            dtDeviceType.LoadDataRow(new object[] { "AT-III-0X00", 0X00, "未知设备" }, true);
            dtDeviceType.LoadDataRow(new object[] { "AT-III-0X21", 0X21, "接收器(GPRS)" }, true);
            dtDeviceType.LoadDataRow(new object[] { "AT-III-0X22", 0X22, "接收器(WIFI)" }, true);
            dtDeviceType.LoadDataRow(new object[] { "AT-III-0X23", 0X23, "中继器" }, true);
            dtDeviceType.LoadDataRow(new object[] { "AT-III-0X24", 0X24, "路由器" }, true);
            dtDeviceType.LoadDataRow(new object[] { "AT-III-0X25", 0X25, "采集器" }, true);
            dtDeviceType.LoadDataRow(new object[] { "AT-III-0X26", 0X26, "接收器(GPRS_mini)" }, true);
            dtDeviceType.LoadDataRow(new object[] { "AT-III-0X27", 0X27, "接收器(X系列)" }, true);

        }

        private void InitdtRecedRecord()
        {
            dtRecedRecord = new DataTable("RecedRecord");
            dtRecedRecord.Columns.Add("IP", Type.GetType("System.String"));
            dtRecedRecord.Columns.Add("Type", Type.GetType("System.String"));
            dtRecedRecord.Columns.Add("Value", Type.GetType("System.Object"));
            dtRecedRecord.Columns.Add("length", Type.GetType("System.Int32"));
            dtRecedRecord.PrimaryKey = new DataColumn[] { dtRecedRecord.Columns["IP"] };
        }

        /// <summary>
        /// 生成指定包头Byte数组
        /// </summary>
        /// <param name="byteHex"></param>
        /// <param name="sIP"></param>
        /// <returns></returns>
        public byte[] GetOrder(string sOrderName, string sReceiverKeyId, string sFlag, string[] sValues, ref string sOrder)
        {
            //string sRet = "";
            byte[] byteHex = null;
            DataRow dr = dtOrderType.Rows.Find(sOrderName);
            if (dr != null)
            {
                //sReceiverKeyId = Convert.ToInt32(sReceiverKeyId).ToString("X4");

                try
                {
                    int iReceiverKeyId = Convert.ToInt32(sReceiverKeyId);
                    byte[] bKeyId = BitConverter.GetBytes(iReceiverKeyId);
                    if (!BitConverter.IsLittleEndian) Array.Reverse(bKeyId);
                    string sData = dr["Head"] + BuildReceiverKeyID(bKeyId, -1, 0x6F) + sFlag;
                    int iValueType = 0;
                    int iValueLen = 0;
                    if (sValues != null && sValues.Length > 0 &&
                        int.TryParse(dr["ValueLen"].ToString(), out iValueLen) && iValueLen != 0 &&
                        int.TryParse(dr["ValueType"].ToString(), out iValueType) && iValueType != 0)
                    {
                        for (int i = 0; i < sValues.Length; i++)
                        {
                            if (sValues[i] != "")
                            {
                                if (iValueType == 1) sData += sValues[i];
                                else if (iValueType == 2) sData += Convert.ToInt32(sValues[i]).ToString("X" + iValueLen * 2);
                                else if (iValueType == 3)
                                {
                                    for (int j = 0; j < sValues[i].Length; j += 2)
                                    {
                                        sData += Convert.ToInt32(sValues[i].Substring(j, 2)).ToString("X" + iValueLen * 2);
                                    }
                                }
                            }
                        }
                    }
                    int iCRCType = (sOrderName == "注册传感器")? 16 : 8;
                    byteHex = GetOrderReceiver(ref sData, Convert.ToInt32(dr["EndTag"].ToString()), iCRCType);
                    sOrder = sData;
                }
                catch { return null; }
            }
            return byteHex;
        }

        /// <summary>
        /// String转16进制带校验Byte数组
        /// </summary>
        /// <param name="byteHex"></param>
        /// <param name="sIP"></param>
        /// <returns></returns>
        public byte[] GetOrderFromString(ref string sOrder)
        {
            string sData = sOrder.Replace(" ", ""); sOrder = "";
            if (sData.Length % 2 != 0) return null;
            int iLen = sData.Length / 2;
            byte[] byteHex = new byte[iLen];
            int j = 0; int iByte = 0;//int iSum = 0;
            for (int i = 0; i < sData.Length; i = i + 2)
            {
                string sByte = sData.Substring(i, 2);
                iByte = Convert.ToInt32(sByte, 16);
                byteHex[j] = Convert.ToByte(iByte);
                sOrder = sOrder + " " + sByte;
                j++;
            }
            return byteHex;
        }

        public byte[] GetOrderFromString(string sOrder)
        {
            return GetOrderFromString(ref sOrder);
        }

        public byte[] GetOrderSMSFromString(ref string sOrder)
        {
            string sData = sOrder.Replace(" ", "");
            int iLen = sData.Length / 2;
            byte[] byteHex = new byte[iLen + 2];
            int j = 0; int iByte = 0;//int iSum = 0;
            for (int i = 0; i < sData.Length; i = i + 2)
            {
                string sByte = sData.Substring(i, 2);
                iByte = Convert.ToInt32(sByte, 16);
                byteHex[j] = Convert.ToByte(iByte);
                //sOrder = sOrder + " " + sByte;
                j++;
            }
            int iCRC;
            string sCRC = GetCRC8(byteHex, 0, out iCRC);// string.Format("{0:X}", iSum);
            byteHex[j] = Convert.ToByte(iCRC);
            sOrder = sOrder + sCRC;
            return byteHex;
        }

        public byte[] GetOrderReceiver(string sOrder, int iEndTag)
        {
            return GetOrderReceiver(ref sOrder, iEndTag, 8);
        }

        /// <summary>
        /// String转16进制带校验Byte数组,自定义结尾
        /// </summary>
        /// <param name="byteHex"></param>
        /// <param name="sIP"></param>
        /// <returns></returns>
        public byte[] GetOrderReceiver(ref string sOrder, int iEndTag, int iCRCType)
        {
            byte[] byteHex = GetOrderFromString(ref sOrder);
            if (byteHex != null)
            {
                string sCRC = string.Empty;
                byte[] byteHex1 = new byte[1];
                if (iCRCType == 8)
                {
                    byteHex1 = new byte[(iEndTag > 0) ? 2 : 1];
                    int iCRC;
                    sCRC = GetCRC8(byteHex, 0, out iCRC);// string.Format("{0:X}", iSum);
                    byteHex1[0] = Convert.ToByte(iCRC);
                }
                else if (iCRCType == 16)
                {
                    byteHex1 = new byte[(iEndTag > 0) ? 3 : 2];
                    byte CRC_H, CRC_L;
                    GetCRC16(byteHex, 0, out CRC_H, out CRC_L);
                    byteHex1[0] = Convert.ToByte(CRC_L);
                    byteHex1[1] = Convert.ToByte(CRC_H);
                    sCRC = CRC_L.ToString("X2") + " " + CRC_H.ToString("X2");
                }
                else return byteHex;
                if (iEndTag > 0)
                {
                    sOrder = sOrder + " " + sCRC + " " + iEndTag.ToString("X2");
                    byteHex1[byteHex1.Length - 1] = Convert.ToByte(iEndTag);
                }
                else sOrder = sOrder + " " + sCRC;
                byteHex = PublicFunc.MergerArray(byteHex, byteHex1);
            }
            return byteHex;
        }

        public bool CRC8(byte[] byteHex, int iLastBit)
        {
            int iCRC;
            string sCRC = GetCRC8(byteHex, iLastBit, out iCRC);
            return byteHex[byteHex.Length - iLastBit] == iCRC;
        }

        public bool CRC16(byte[] byteHex, int iLastBit)
        {
            byte CRC_H, CRC_L;
            GetCRC16(byteHex, iLastBit, out CRC_H, out CRC_L);
            return byteHex[byteHex.Length - iLastBit + 1] == CRC_H && byteHex[byteHex.Length - iLastBit] == CRC_L;
        }

        private string GetCRC8(byte[] byteHex, int iLastBit, out int iCRC)
        {
            int iSum = 0; int iLen = byteHex.Length - iLastBit;
            for (int i = 0; i < iLen; i++)
            {
                iSum = iSum + Convert.ToInt32(byteHex[i]);
            }
            string sCRC = string.Format("{0:X}", iSum);
            if (sCRC.Length < 2) sCRC = sCRC.PadLeft(2, '0');
            else if (sCRC.Length > 2) sCRC = sCRC.Substring(sCRC.Length - 2, 2);

            iCRC = Convert.ToInt32(sCRC, 16);
            return sCRC;
        }

        //private string GetCRC16(byte[] byteHex, int iLastBit, out byte CRC_H, out byte CRC_L)
        //{
        //    int iSum = 0; int iLen = byteHex.Length - iLastBit;
        //    for (int i = 0; i < iLen; i++)
        //    {
        //        iSum = iSum + byteHex[i];
        //    }
        //    string sCRC = string.Format("{0:X}", iSum);
        //    if (sCRC.Length < 4) sCRC = sCRC.PadLeft(4, '0');
        //    else if (sCRC.Length > 2) sCRC = sCRC.Substring(sCRC.Length - 4, 4);

        //    CRC_L = Convert.ToByte(sCRC.Substring(0, 2), 16);
        //    CRC_H = Convert.ToByte(sCRC.Substring(2, 2), 16);
        //    return sCRC;

        //}

        public byte[] GetCRC16(byte[] byteHex, int iLastBit, out byte CRC_H, out byte CRC_L)
        {
            CRC_L = 0xFF;
            CRC_H = 0xFF;   //CRC寄存器 
            byte SH;
            byte SL;
            byte[] temp = byteHex;
            int j;

            for (int i = 0; i < temp.Length - iLastBit; i++)
            {
                CRC_L = (byte)(CRC_L ^ temp[i]);     //每一个数据与CRC寄存器进行异或 
                for (j = 0; j < 8; j++)
                {
                    SH = (byte)(CRC_H & 0x01);
                    SL = (byte)(CRC_L & 0x01);

                    CRC_H = (byte)(CRC_H >> 1);      //高位右移一位
                    CRC_H = (byte)(CRC_H & 0x7F);
                    CRC_L = (byte)(CRC_L >> 1);      //低位右移一位 
                    CRC_L = (byte)(CRC_L & 0x7F);

                    if (SH == 0x01)                  //如果高位字节最后一位为1 
                    {
                        CRC_L = (byte)(CRC_L | 0x80);//则低位字节右移后前面补1 
                    }                                //否则自动补0 
                    if (SL == 0x01)                  //如果LSB为1,则与多项式码进行异或 
                    {
                        CRC_H = (byte)(CRC_H ^ 0xA0);
                        CRC_L = (byte)(CRC_L ^ 0x01);
                    }
                }
            }
            byte[] CRC = new byte[2];
            CRC[0] = CRC_L;       //CRC高位 
            CRC[1] = CRC_H;       //CRC低位 
            return PublicFunc.MergerArray(byteHex, CRC);
        }

        /// <summary>
        /// Byte数组取反
        /// </summary>
        /// <param name="byteHex"></param>
        /// <param name="sIP"></param>
        /// <returns></returns>
        public byte[] NOT(byte[] byteHex)
        {
            for (int i = 0; i < byteHex.Length; i++)
            {
                byteHex[i] = (byte)~byteHex[i];
            }
            return byteHex;
        }

        /// <summary>
        /// 清理指定设备接收缓存表
        /// </summary>
        /// <param name="byteHex"></param>
        /// <param name="sIP"></param>
        /// <returns></returns>
        public void CleanRecedRecord(string sIP)
        {
            DataRow drRecedRecord = dtRecedRecord.Rows.Find(sIP);
            if (drRecedRecord != null) dtRecedRecord.Rows.Remove(drRecedRecord);
        }

        private string GetReceiverKeyID(byte[] byteHex, int iBegin, int iType)
        {
            string sReceiverID = "";
            if (byteHex.Length > 4 + iBegin)
            {
                //sReceiverID = BitConverter.ToInt32(new byte[] { byteHex[iBegin + 4], byteHex[iBegin + 3], byteHex[iBegin + 2], byteHex[iBegin + 1] }, 0).ToString();
                switch (iType)
                {
                    case 0x5F:
                    case 0x20: sReceiverID = BitConverter.ToInt32(new byte[] { byteHex[iBegin + 4], byteHex[iBegin + 3], byteHex[iBegin + 2], byteHex[iBegin + 1] }, 0).ToString(); break;//大端模式
                    case 0x6F:
                    case 0x50:
                    case 0x60:
                    case 0x61:
                    case 0x62:
                        sReceiverID = BitConverter.ToInt32(new byte[] { byteHex[iBegin + 1], byteHex[iBegin + 2], byteHex[iBegin + 3], byteHex[iBegin + 4] }, 0).ToString(); break;//小端模式
                    default:
                        break;
                }
            }
            return sReceiverID.PadLeft(10, '0');
        }

        private int GetSensorID(byte[] byteHex, ref int iBegin, int iAddrMode)
        {
            int iSensorID = 0;
            if (byteHex.Length > 4 + iBegin)
            {
                if (iAddrMode == 0x00)
                {
                    iSensorID = BitConverter.ToInt32(new byte[] { byteHex[iBegin], byteHex[iBegin + 1], byteHex[iBegin + 2], byteHex[iBegin + 3] }, 0);//小端模式 
                    iBegin += 4;
                }
                else if (iAddrMode == 0x10)
                {
                    iSensorID = byteHex[iBegin];
                    iBegin += 1;
                }
            }
            return iSensorID;
        }

        public static string BuildReceiverKeyID(byte[] byteHex, int iBegin, int iType)
        {
            string sReceiverID = "";
            if (byteHex.Length >= 4 + iBegin)
            {
                if (iType == 0x5F) sReceiverID = (byteHex[iBegin + 1] * 256 + byteHex[iBegin + 2]).ToString("X4");
                else if (iType == 0x6F) sReceiverID = BitConverter.ToString(new byte[] { byteHex[iBegin + 1], byteHex[iBegin + 2], byteHex[iBegin + 3], byteHex[iBegin + 4] }, 0);
            }
            return sReceiverID.Replace("-", "");
        }

        //private int GetReceiverID(byte[] byteHex, int iBegin)
        //{
        //    int iReceiverId = 0;
        //    if (byteHex.Length > 2 + iBegin)
        //    {
        //        iReceiverId = byteHex[iBegin + 11] * 256 + byteHex[iBegin + 12];
        //    }
        //    return iReceiverId;
        //}

        private bool GetGatherDate(byte[] byteHex, ref int iBegin, ref string sGPS_Date, double iHous)
        {
            bool b = true;
            sGPS_Date = "20" + byteHex[iBegin].ToString("00") + "-" + byteHex[iBegin + 1].ToString("00") + "-" + byteHex[iBegin + 2].ToString("00") + " " +
                    byteHex[iBegin + 3].ToString("00") + ":" + byteHex[iBegin + 4].ToString("00") + ":" + byteHex[iBegin + 5].ToString("00");
            iBegin += 6;
            DateTime tDate;
            if (DateTime.TryParse(sGPS_Date, out tDate) && (DateTime.Now - tDate).TotalDays < 365)
            {
                sGPS_Date = PublicFunc.GetUniformDateString(tDate.AddHours(iHous));//加8小时
            }
            else
            {
                //tDate = DateTime.Now;
                //sGPS_Date = PublicFunc.GetUniformDateString(tDate);//加8小时
                b = false;
            }
            return b;
        }

        /// <summary>
        /// 刷新接收器列表
        /// </summary>
        /// <param name="byteHex"></param>
        /// <param name="sIP"></param>
        /// <returns></returns>
        //private void RefreshReceiver(string sIP, int iReceiverId, string sReceiverID, string sPhone, bool bUpdateTime)
        //{
        //    lock (dtReceiver)  //换成HASHTABLE
        //    {
        //        DataRow dr = dtReceiver.Rows.Find(iReceiverId);
        //        string sql = "";

        //        if (dr == null)
        //        {
        //            int iType = (sIP.StartsWith("COM")) ? 1 : 0;
        //            sql = "insert into Receiver(ReceiverId,ReceiverID,Port,Type,Phone) values(" +
        //                iReceiverId + ",'" + sReceiverID + "','" + sIP + "'," + iType + ",'" + sPhone + "')";
        //            dr = AddReceiver(sIP, iReceiverId, sReceiverID, iType, sPhone);
        //        }
        //        else
        //        {
        //            string sValue = "";
        //            if (dr["Port"].ToString() != sIP)
        //            {
        //                if (sIP.StartsWith("COM")) dr["Type"] = 1;
        //                else dr["Type"] = 0;
        //                dr["Port"] = sIP;
        //                sValue += "Port='" + sIP + "',Type=" + dr["Type"] + ",";
        //            }
        //            if (dr["ReceiverID"].ToString() != sReceiverID && sReceiverID != "")
        //            {
        //                dr["ReceiverID"] = sReceiverID;
        //                sValue += "ReceiverID='" + sReceiverID + "',";
        //            }
        //            if (dr["Phone"].ToString() != sPhone && sPhone != "")
        //            {
        //                dr["Phone"] = sPhone;
        //                sValue += "Phone='" + sPhone + "',";
        //            }
        //            if (sValue != "") sql = "update Receiver set " + sValue.TrimEnd(',') + " where ReceiverId=" + iReceiverId;
        //        }
        //        if (sql != "") dbo.ExcuteSQL(sql);
        //        if (bUpdateTime) dr["GatherFrequency"] = DateTime.Now.ToString();
        //        if (dr["Online"].ToString() != dbo.GetLanguage(195)) dr["Online"] = dbo.GetLanguage(195);//"在线";"在线"

        //    }
        //}

        /// <summary>
        /// 回应接收器
        /// </summary>
        /// <param name="sIP"></param>
        /// <param name="sHead"></param>
        /// <param name="byteHex"></param>
        /// <returns></returns>
        public byte[] RespondReceiver(string sIP, string sHead, byte[] byteHex, string[] sErrCode = null)
        {
            //Thread.Sleep(30000);
            string sOrder;
            string sReceiverID = "";
            switch (sHead)
            {
                case "6A01":
                case "6855":
                    int index = byteHex[4];
                    string sFlag = "0";
                    if (sHead == "6A01")
                    {
                        sFlag = Convert.ToString(byteHex[7], 2).PadLeft(8, '0')[7].ToString();
                        sReceiverID = BuildReceiverKeyID(byteHex, 7, 0x6F);
                    }
                    else if (sHead == "6855")
                    {
                        sFlag = Convert.ToString(byteHex[6], 2).PadLeft(8, '0')[7].ToString();
                        sReceiverID = BuildReceiverKeyID(byteHex, 10, 0x5F);
                    }
                    sOrder = sHead + index.ToString("X2") + ((sErrCode != null) ? "" : Convert.ToInt32(sFlag).ToString("X2")) + sReceiverID;
                    if (sFlag == "1" || sErrCode != null)
                    {
                        string sDate = DateTime.Now.ToUniversalTime().ToString("yyMMddHHmmss");
                        //sOrder += string.Format("{0:x}", Convert.ToInt32(sDate)).PadLeft(2, '0');
                        for (int i = 0; i < sDate.Length; i += 2)
                        {
                            sOrder += Convert.ToInt32(sDate.Substring(i, 2)).ToString("X2");
                        }
                    }
                    break;
                case "6A10":
                case "6866":
                    int iPacketindex = 0;
                    if (sHead == "6A10")
                    {
                        iPacketindex = byteHex[10] * 256 + byteHex[11];
                        sReceiverID = BuildReceiverKeyID(byteHex, 1, 0x6F);
                    }
                    else if (sHead == "6866")
                    {
                        iPacketindex = byteHex[6] * 256 + byteHex[7];
                        sReceiverID = BuildReceiverKeyID(byteHex, 18, 0x5F);
                    }
                    sOrder = sHead + sReceiverID + iPacketindex.ToString("X4");
                    break;
                default:
                    {
                        sOrder = "";
                        break;
                    }
            }
            if (sErrCode != null) sOrder += Convert.ToInt32(string.Join("", sErrCode), 2).ToString("X2");

            //6.2协议新增
            if (sErrCode != null && (byteHex[5] == 0x62 && sErrCode[0]=="1"))
            {
                sOrder += 4.ToString("X2");
            }

            return GetOrderReceiver(ref sOrder, 0x0d, 8);
        }

        public int GetHexLen(string sHead, byte[] byteHex, int index)
        {
            int iLen = 0;
            int iMode = byteHex[6];
            switch (sHead)
            {
                case "6A01":
                    iLen = BitConverter.ToInt16(new byte[] { byteHex[index + 2], byteHex[index + 3] }, 0) + 4;
                    break;
                case "6A10":
                    iLen = BitConverter.ToInt16(new byte[] { byteHex[index + 6], byteHex[index + 7] }, 0) + 8;
                    break;
                case "6A1F":
                    iLen = BitConverter.ToInt16(new byte[] { byteHex[index + 7], byteHex[index + 8] }, 0) * 4 + 12;
                    break;
                case "6A21":
                    int itLen = byteHex[7];
                    iLen = 6 + itLen + 4;
                    break;
                case "6A20":
                    if (iMode == 0x00)
                    {
                        iLen = 12 + 4;
                    }
                    else iLen = 9;

                    break;
                case "6A23":
                    if (iMode == 0x00)
                    {
                        iLen = 9 + 4;
                    }
                    else iLen = 9;

                    break;
                case "6A24":
                    if (iMode == 0x00)
                    {
                        itLen = 0;
                        string sExistflagn = Convert.ToString(byteHex[7], 2).PadLeft(8, '0');
                        foreach (var s in sExistflagn)
                        {
                            if (s == '1') itLen = +4;
                        }
                        iLen = 6 + itLen + 4;
                    }
                    else iLen = 9;

                    break;

                case "6855":
                case "6866":
                case "6899":
                    iLen = byteHex[index + 2] * 256 + byteHex[index + 3] + 4;
                    break;
                    //case "6877":
                    //    iLen = 5;
                    //    break;
                    //case "6888":
                    //    iLen = 5;
                    //    break;
                    //case "68AA":
                    //    iLen = 5;
                    //    break;
                    //case "68BB":
                    //    iLen = 5;
                    //    break;
                    //case "68CC":
                    //    iLen = 24;
                    //    break;
                    //case "68DD":
                    //    iLen = 5;
                    //    break;

            }
            return iLen;
        }

        /// <summary>
        /// 贴包
        /// </summary>
        /// <param name="byteHex"></param>
        /// <param name="sIP"></param>
        /// <returns></returns>
        public string CollectData(string sIP, byte[] byteHex)
        {
            string sRet = "";
            string sHead = "";

            bool bChanged = false;
            int iRec = byteHex.Length;
            if ((byteHex[0] == 0x5F || byteHex[0] == 0x6F)
                && (iRec == 5 || iRec == 6))//心跳包
            {
                int iReceiverID = 0;
                string sReceiverKeyID = GetReceiverKeyID(byteHex, iRec - 5, byteHex[0]);
                foreach (DataRow dr in dtReceiver.Rows)
                {
                    if (dr["ReceiverID"].ToString() == sReceiverKeyID)
                    {
                        iReceiverID = Convert.ToInt32(dr["ReceiverId"]);
                        break;
                    }
                }
                MyReceiver myReceiver = htRecriver[sReceiverKeyID];
                myReceiver.RefreshReceiver(sIP);
                //RefreshReceiver(sIP, iReceiverId, sReceiverID, "", false);
                sReceiverKeyID = byteHex[1].ToString("X2") + byteHex[2].ToString("X2") + byteHex[3].ToString("X2") + byteHex[4].ToString("X2");
                if (byteHex[0] == 0x5F)
                {
                    sHead = "A0";
                }
                else if (byteHex[0] == 0x6F)
                {
                    sHead = "90";
                }
                netSend(sIP, GetOrderFromString(sHead + sReceiverKeyID));
                return sRet;
            }
            int index;
            for (index = 0; index < iRec - 8; index++)
            {
                bChanged = false;
                sHead = byteHex[index + 1].ToString("X2") + byteHex[index].ToString("X2");
                int iLen = GetHexLen(sHead, byteHex, index);
                if (sLastHead == "6866" || sLastHead == "6A10" && iRec > iLen + 1)
                {
                    bChanged = false;
                    index = 0;
                    break;
                    //index = iRec - 8;
                }
                else if (iLen > 0)
                {
                    iCurLen = iLen;
                    sLastHead = sHead;
                    bChanged = true;
                }

                if (bChanged) break;
            }
            if (iRec - index >= iCurLen && iCurLen > 0)
            {
                byte[] OnePacket = new byte[iCurLen];
                Buffer.BlockCopy(byteHex, index, OnePacket, 0, iCurLen);
                if (iRec - index - iCurLen > 8)
                {
                    byte[] OtherPacket = new byte[byteHex.Length - iCurLen];
                    Buffer.BlockCopy(byteHex, index + iCurLen, OtherPacket, 0, byteHex.Length - iCurLen);
                    sRet = CollectData(sIP, OtherPacket);
                }
                sRet = AnalysisData(sIP, OnePacket);
            }
            else if (iCurLen > 0)
            {
                DataRow drRecedRecord = dtRecedRecord.Rows.Find(sIP);

                if (drRecedRecord == null)
                {
                    dtRecedRecord.Rows.Add(sIP, sHead, byteHex, iRec);
                }
                else
                {
                    if (bChanged)
                    {
                        dtRecedRecord.Rows.Remove(drRecedRecord);
                        dtRecedRecord.Rows.Add(sIP, sHead, byteHex, iRec);
                    }
                    else
                    {
                        int iRecord = int.Parse(drRecedRecord["length"].ToString());
                        byte[] AllPacket = new byte[iRecord + iRec];
                        Buffer.BlockCopy((byte[])drRecedRecord["Value"], 0, AllPacket, 0, iRecord);
                        Buffer.BlockCopy(byteHex, 0, AllPacket, iRecord, iRec);
                        if (AllPacket.Length >= iCurLen)
                        {
                            sRet = CollectData(sIP, AllPacket);
                        }
                        else
                        {
                            drRecedRecord["Value"] = AllPacket;
                        }
                    }
                }
            }
            return sRet;
        }

        /// <summary>
        /// 解析协议
        /// </summary>
        /// <param name="byteHex"></param>
        /// <param name="sIP"></param>
        /// <returns></returns>
        public string AnalysisData(string sIP, byte[] byteHex)
        {
            sLastHead = "";
            iCurLen = 0;

            PC.SendMessage(frmHandle, PC.WM_Received, 100, 100);

            bool bOK = true;
            string sRet = "";
            if (byteHex == null || byteHex.Length == 0) return sRet;//无效数据
            string sHead = "";
            if (byteHex.Length > 2) sHead = byteHex[1].ToString("X2") + byteHex[0].ToString("X2");
            string sReceiverKeyID = "";
            //if (iReceiverId >= 0x3E8) return sRet;//超出范围

            if (sHead != "6A01" && sHead != "6A10" && sHead != "6A1F" && !CRC8(byteHex, 2))
                sRet = "CRC " + dbo.GetLanguage(103) + "Error";
            else
                switch (sHead)
                {

                    #region 6855//采集数据
                    case "6855":
                        sReceiverKeyID = GetReceiverKeyID(byteHex, 6, 0x20);

                        if (!htRecriver.ContainsKey(sReceiverKeyID)) return dbo.GetLanguage(427) + "Error";
                        MyReceiver myReceiver = htRecriver[sReceiverKeyID];
                        StringBuilder sbGatherData = new StringBuilder();
                        StringBuilder sbMapData = new StringBuilder();

                        PC.SendMessage(frmHandle, PC.WM_GatherData, myReceiver.iReceiverKeyID, 1);
                        sRet = GatherData_GPS_20(sIP, byteHex, myReceiver, 13, ref sbGatherData, ref sbMapData);
                        bOK = !sRet.EndsWith("Error");

                        if (bOK && sbGatherData.Length > 0)
                        {
                            PC.SendMessage(frmHandle, PC.WM_GatherData, myReceiver.iReceiverKeyID, 2);
                            myReceiver.WirteData(sbGatherData.ToString() + sbMapData.ToString(), sGatherNo, sIP);
                            PC.SendMessage(frmHandle, PC.WM_GatherData, myReceiver.iReceiverKeyID, 3);
                            sRet = dbo.GetLanguage(71) + "OK";//接收器数据采集完毕
                        }
                        else if (sRet == "") sRet = dbo.GetLanguage(305) + "Error";

                        if (bOK)
                        {
                            netSend(sIP, RespondReceiver(sIP, sHead, byteHex));
                            myReceiver.RefreshReceiver(sIP);
                        }

                        //RefreshReceiver(sIP, iReceiverId, sReceiverID, "", true);
                        //MarkWarnData(dbo, sGatherNo);
                        PC.SendMessage(frmHandle, PC.WM_GatherData, myReceiver.iReceiverKeyID, 4);
                        break;
                    #endregion

                    #region 6866//补发数据
                    case "6866":
                        sReceiverKeyID = GetReceiverKeyID(byteHex, 8 + 6, 0x20);

                        if (!htRecriver.ContainsKey(sReceiverKeyID)) return dbo.GetLanguage(427) + "Error";
                        myReceiver = htRecriver[sReceiverKeyID];

                        sbGatherData = new StringBuilder();
                        sbMapData = null;

                        int iPaccketTotal = byteHex[4] * 256 + byteHex[5];
                        int iPacketindex = byteHex[6] * 256 + byteHex[7];

                        PC.SendMessage(frmHandle, PC.WM_GatherData, myReceiver.iReceiverKeyID, 1);

                        for (int iBegin = 8; iBegin < byteHex.Length - 4; iBegin++)
                        {
                            if (byteHex[iBegin] == 0x55 && byteHex[iBegin + 1] == 0x68)
                            {
                                int iDataLen = byteHex[iBegin + 2] * 256 + byteHex[iBegin + 3];

                                sRet = GatherData_GPS_20(sIP, byteHex, myReceiver, iBegin + 13, ref sbGatherData, ref sbMapData);
                                //if (sRet.EndsWith("Error")) { bOK = false; break; }
                                iBegin += iDataLen + 2;
                            }
                        }
                        if (bOK && sbGatherData.Length > 0)
                        {
                            PC.SendMessage(frmHandle, PC.WM_GatherData, myReceiver.iReceiverKeyID, 2);
                            myReceiver.WirteData(sbGatherData.ToString(), sGatherNo, sIP);
                            PC.SendMessage(frmHandle, PC.WM_GatherData, myReceiver.iReceiverKeyID, 3);
                            sRet = dbo.GetLanguage(89) + "," + dbo.GetLanguage(476) + "OK";//补发数据，保存成功!";
                        }
                        else if (sRet == "") sRet = dbo.GetLanguage(305) + "Error";
                        netSend(sIP, RespondReceiver(sIP, sHead, byteHex));
                        myReceiver.RefreshReceiver(sIP);
                        PC.SendMessage(frmHandle, PC.WM_GatherData, myReceiver.iReceiverKeyID, 4);
                        break;
                    #endregion


                    #region 6A01//采集数据
                    case "6A01":
                        string[] sErrFlag = new string[] { "0", "0", "0", "0" };
                        if (!CRC16(byteHex, 3))
                        {
                            sErrFlag[3] = "1";
                            sRet = "CRC " + dbo.GetLanguage(103) + "Error";
                        }
                        sReceiverKeyID = GetReceiverKeyID(byteHex, 7, byteHex[5]);
                        myReceiver = htRecriver[sReceiverKeyID];
                        if (!htRecriver.ContainsKey(sReceiverKeyID)) return dbo.GetLanguage(427) + "Error";
                        sbGatherData = new StringBuilder();
                        sbMapData = new StringBuilder();

                        PC.SendMessage(frmHandle, PC.WM_GatherData, myReceiver.iReceiverKeyID, 1);
                        switch (byteHex[5])//协议版本
                        {
                            case 0x50:
                                sRet = GatherData_GPS_50(sIP, byteHex, myReceiver, 12, ref sbGatherData, ref sbMapData);
                                sErrFlag = null;
                                break;
                            case 0x60:
                            case 0x61:
                                sRet = GatherData_GPS_60(sIP, byteHex, myReceiver, 12, ref sbGatherData, ref sbMapData);
                                if (sRet.EndsWith("TimeError")) sErrFlag[1] = "1";
                                else if (sRet.EndsWith("Error")) sErrFlag[0] = "1";
                                break;
                                //6.2协议
                            case 0x62:
                                sRet = GatherData_GPS_60(sIP, byteHex, myReceiver, 12, ref sbGatherData, ref sbMapData);
                                sErrFlag= new string[] {"0", "0", "0", "0", "0", "0", "0", "0"};
                                if (!CRC16(byteHex, 3))
                                {
                                    sErrFlag[7] = "1";
                                }
                                if (sRet.EndsWith("TimeError")) sErrFlag[5] = "1";
                                else if (sRet.EndsWith("Error")) sErrFlag[4] = "1";
                                break;
                            default:
                                break;
                        }
                        bOK = !sRet.EndsWith("Error");

                        if (bOK && sbGatherData.Length > 0)
                        {
                            PC.SendMessage(frmHandle, PC.WM_GatherData, myReceiver.iReceiverKeyID, 2);
                            myReceiver.WirteData(sbGatherData.ToString() + sbMapData.ToString(), sGatherNo, sIP);
                            PC.SendMessage(frmHandle, PC.WM_GatherData, myReceiver.iReceiverKeyID, 3);
                            sRet = dbo.GetLanguage(71) + "OK";//接收器数据采集完毕
                        }
                        else if (sRet == "") sRet = dbo.GetLanguage(305) + "Error";

                        if (bOK) myReceiver.RefreshReceiver(sIP);

                        #region 查询接收仪是否有修改
                        bool isImmeSentOrder = false;
                        bool isImmediateAlarm = true;
                        DataTable dtReceiver = null;
                        //6.2协议新增
                        if (byteHex[5] == 0x62)
                        {
                            dtReceiver =
                                dbo.GetDataTableBySql(
                                    string.Format(@"Select *,'' Online,'' GatherFrequency From Sys_Receiver WHERE  KeyId={0} AND IsUpdate='True'",
                                        myReceiver.iReceiverKeyID), "IsUpdate");

                            if (dtReceiver.Rows.Count > 0)
                            {
                                if (sErrFlag != null) sErrFlag[0] = "1";
                                isImmediateAlarm = PublicMethod.GetBool(dtReceiver.Rows[0]["IsImmediateAlarm"]);
                                isImmeSentOrder = true;
                            }
                        }

                        #endregion


                        netSend(sIP, RespondReceiver(sIP, sHead, byteHex, sErrFlag));
                        //立即发送更新命令
                        if (isImmeSentOrder)
                        {
                            if (dtReceiver.Rows.Count > 0)
                            {
                                myReceiver.RefreshParam(dtReceiver.Rows[0]);
                            }

                            Thread.Sleep(3000);

                            AddOrder(myReceiver, "02", myReceiver.GetSensor(1), "注册传感器",sIP);

                            Thread.Sleep(6000);

                            AddOrder(myReceiver, "01", myReceiver.GetCycle(), "设置周期", sIP);

                            Thread.Sleep(6000);

                            string flag = "00" + ((isImmediateAlarm) ? "83" : "80");//flag
                            AddOrder(myReceiver, flag, myReceiver.GetThreshold(isImmediateAlarm), "设置阀值", sIP);

                            Thread.Sleep(6000);

                            AddOrder(myReceiver, "01", myReceiver.GetDateTime(), "设置时钟", sIP);

                            dbo.ExcuteSQL("Update Sys_Receiver set IsUpdate='False' where IsUpdate='True' and KeyId=" + myReceiver.iReceiverKeyID);
                        }

                        PC.SendMessage(frmHandle, PC.WM_GatherData, myReceiver.iReceiverKeyID, 4);
                        break;
                    #endregion

                    #region 6A10//补发数据
                    case "6A10":
                        sErrFlag = new string[] { "0", "0", "0", "0" };
                        if (!CRC16(byteHex, 3))
                        {
                            sErrFlag[3] = "1";
                            sRet = "CRC " + dbo.GetLanguage(103) + "Error";
                        }
                        sReceiverKeyID = GetReceiverKeyID(byteHex, 1, byteHex[12 + 5]);
                        myReceiver = htRecriver[sReceiverKeyID];
                        if (!htRecriver.ContainsKey(sReceiverKeyID)) return dbo.GetLanguage(427) + "Error";

                        sbGatherData = new StringBuilder();
                        sbMapData = null;

                        iPaccketTotal = byteHex[8] * 256 + byteHex[9];
                        iPacketindex = byteHex[10] * 256 + byteHex[11];

                        PC.SendMessage(frmHandle, PC.WM_GatherData, myReceiver.iReceiverKeyID, 1);

                        for (int iBegin = 12; iBegin < byteHex.Length - 4; iBegin++)
                        {
                            if (byteHex[iBegin] == 0x01 && byteHex[iBegin + 1] == 0x6A)
                            {
                                int iDataLen = BitConverter.ToInt16(new byte[] { byteHex[iBegin + 2], byteHex[iBegin + 3] }, 0);
                                switch (byteHex[iBegin + 5])//协议版本
                                {
                                    case 0x50:
                                        sRet = GatherData_GPS_50(sIP, byteHex, myReceiver, iBegin + 12, ref sbGatherData, ref sbMapData);
                                        if (sErrFlag != null) sErrFlag = null;
                                        break;
                                    case 0x60:
                                    case 0x61:
                                    case 0x62:
                                        sRet = GatherData_GPS_60(sIP, byteHex, myReceiver, iBegin + 8, ref sbGatherData, ref sbMapData);
                                        if (sRet.EndsWith("TimeError")) sErrFlag[1] = "1";
                                        else if (sRet.EndsWith("Error")) sErrFlag[0] = "1";
                                        break;
                                    default:
                                        break;
                                }
                                //if (sRet.EndsWith("Error")) { bOK = false; break; }
                                iBegin += iDataLen + 2;
                            }
                        }
                        if (bOK && sbGatherData.Length > 0)
                        {
                            PC.SendMessage(frmHandle, PC.WM_GatherData, myReceiver.iReceiverKeyID, 2);
                            myReceiver.WirteData(sbGatherData.ToString(), sGatherNo, sIP);
                            PC.SendMessage(frmHandle, PC.WM_GatherData, myReceiver.iReceiverKeyID, 3);
                            sRet = dbo.GetLanguage(89) + "," + dbo.GetLanguage(476) + "OK";//补发数据，保存成功!";
                        }
                        else if (sRet == "") sRet = dbo.GetLanguage(305) + "Error";

                        myReceiver.RefreshReceiver(sIP);
                        netSend(sIP, RespondReceiver(sIP, sHead, byteHex, sErrFlag));
                        PC.SendMessage(frmHandle, PC.WM_GatherData, myReceiver.iReceiverKeyID, 4);
                        break;
                    #endregion

                    #region 6A1F//注册传感器
                    case "6A1F":
                        if (!CRC16(byteHex, 3)) sRet = "CRC " + dbo.GetLanguage(103) + "Error";
                        sReceiverKeyID = GetReceiverKeyID(byteHex, 1, 0x50);
                        byte bFlag = byteHex[3];
                        switch (bFlag)
                        {
                            case 0x00: //对上位机发送查询信息的回应
                                string sSensorIds = "";
                                myReceiver = htRecriver[sReceiverKeyID];
                                int iLen = BitConverter.ToInt16(new byte[] { byteHex[7], byteHex[8] }, 0) * 4 + 9;
                                for (int i = 9; i < iLen;)
                                {
                                    sSensorIds += GetSensorID(byteHex, ref i, 0x00) + ",";
                                }
                                myReceiver.MateSensor(sSensorIds.TrimEnd(','));
                                PC.SendMessage(frmHandle, PC.WM_ResponseOrder, myReceiver.iReceiverKeyID, 0x6A20);

                                break;
                            case 0x01: //主动上传标示 
                                break;
                            case 0x02: //对上位机设置注册信息的回应
                                sRet = "传感器注册成功!";
                                break;
                            case 0x03: //对上位机下发的清除注册信息的回应
                                sRet = "清除传感器注册信息成功!";
                                break;
                            default:
                                break;
                        }
                        //string sOrder = sHead + BuildReceiverKeyID(byteHex, 1, 0x6F) + bFlag.ToString("X2");
                        //netSend(sIP, GetOrderReceiver(ref sOrder, 0x0d));
                        break;
                    #endregion

                    #region 6A20//设置时钟
                    case "6A20":
                        sReceiverKeyID = GetReceiverKeyID(byteHex, 1, 0x50);
                        if (byteHex[6] == 0x01)
                            sRet = dbo.GetLanguage(60);// "接收仪时钟设置成功!";
                        else if (byteHex[6] == 0x00)
                        {
                            myReceiver = htRecriver[sReceiverKeyID];
                            string sDate = "";
                            int index = 8;
                            if (!GetGatherDate(byteHex, ref index, ref sDate, 0.0)) break;
                            //DateTime rt = DateTime.FromBinary(BitConverter.ToInt64(byteHex, 8));
                            myReceiver.SetDateTime(byteHex[7], sDate);
                            PC.SendMessage(frmHandle, PC.WM_ResponseOrder, myReceiver.iReceiverKeyID, 0x6A20);
                        }
                        break;
                    #endregion

                    #region 6A21//获取参数
                    case "6A21":
                        sReceiverKeyID = GetReceiverKeyID(byteHex, 1, 0x50);
                        myReceiver = htRecriver[sReceiverKeyID];
                        myReceiver.SetInfo(byteHex[6], Encoding.ASCII.GetString(byteHex, 8, byteHex[7]));
                        PC.SendMessage(frmHandle, PC.WM_ResponseOrder, myReceiver.iReceiverKeyID, 0x6A21);
                        break;
                    #endregion

                    #region 6A23//设置周期
                    case "6A23":
                        sReceiverKeyID = GetReceiverKeyID(byteHex, 1, 0x50);
                        if (byteHex[6] == 0x01)
                            sRet = dbo.GetLanguage(238);// "接收仪采集周期设置成功!";
                        else if (byteHex[6] == 0x00)
                        {
                            myReceiver = htRecriver[sReceiverKeyID];
                            myReceiver.SetCycle(BitConverter.ToInt16(new byte[] { byteHex[7], byteHex[8] }, 0), BitConverter.ToInt16(new byte[] { byteHex[9], byteHex[10] }, 0));
                            PC.SendMessage(frmHandle, PC.WM_ResponseOrder, myReceiver.iReceiverKeyID, 0x6A23);
                        }
                        break;
                    #endregion

                    #region 6A24//设置门限
                    case "6A24":
                        sReceiverKeyID = GetReceiverKeyID(byteHex, 1, 0x50);
                        if (byteHex[6] == 0x01)
                            sRet = dbo.GetLanguage(242);//"接收仪报警门限设置成功!";
                        else if (byteHex[6] == 0x00)
                        {
                            myReceiver = htRecriver[sReceiverKeyID];
                            string sExistFlag = Convert.ToString(byteHex[7], 2).PadLeft(8, '0');
                            byte[] byteTemp = new byte[byteHex.Length - 8];
                            Array.Copy(byteHex, 8, byteTemp, 0, byteTemp.Length);
                            myReceiver.SetThreshold(sExistFlag, byteTemp);
                            PC.SendMessage(frmHandle, PC.WM_ResponseOrder, myReceiver.iReceiverKeyID, 0x6A24);
                        }
                        break;
                    #endregion

                    #region 6A25//重启设备
                    case "6A25":
                        sRet = dbo.GetLanguage(359);// "接收仪重启成功!";
                        break;
                    #endregion

                    default:
                        sRet = dbo.GetLanguage(327);// "未知的命令格式,执行失败!";
                        break;
                }

            PC.SendMessage(frmHandle, PC.WM_Received, 100, 200);
            return dbo.GetLanguage(237) + "(" + sReceiverKeyID + ");" + sRet;
        }

        /// <summary>
        /// 解析6855 
        /// V2.0
        /// </summary>
        /// <param name="psIP"></param>
        /// <param name="byteHex"></param>
        /// <param name="iReceiverId"></param>
        /// <param name="iBegin"></param>
        /// <param name="LSQL1"></param>
        /// <param name="LSQL2"></param>
        /// <returns></returns>
        private string GatherData_GPS_20(string psIP, byte[] byteHex, MyReceiver myReceiver, int iBegin, ref StringBuilder sbGatherData, ref StringBuilder sbMapData)//协议3.0
        {
            string sFlag, sflag, sGPS_Date = "", sRet = "";

            string sGatherDate = PublicFunc.GetUniformDateString(DateTime.Now);
            if (sGatherNo == "" || !blDataFromCall) sGatherNo = sGatherDate;// return "未采集数据!";

            //int iSetClick = 0;
            //int iBegin = 12;
            double dLat = 0.0;
            double dLng = 0.0;
            string[] sM = null;
            List<string[]> LsM = new List<string[]>();

            sFlag = Convert.ToString(byteHex[iBegin - 7], 2).PadLeft(8, '0');//byteHex[iBegin - 8] * 256 + 

            if (sFlag[2].ToString() == "1")//时间格式
            {
                if (!GetGatherDate(byteHex, ref iBegin, ref sGPS_Date, 8)) return dbo.GetLanguage(491) + dbo.GetLanguage(369) + "(" + sGPS_Date + ")";// +"Error";
            }
            else sGPS_Date = sGatherDate;

            //if (myReceiver.IsExistData(sGPS_Date)) return dbo.GetLanguage(128);//已存在相同数据

            if (sFlag[3].ToString() == "1")//定位信息
            {
                if (sFlag[4].ToString() == "1")//定位方式(精准)
                {
                    dLat = byteHex[iBegin] + Convert.ToDouble(byteHex[iBegin + 1]) / 60 + Convert.ToDouble((byteHex[iBegin + 2] * 256 + byteHex[iBegin + 3])) / 3600000 - AmateParam.Units.dLat;
                    dLng = byteHex[iBegin + 4] + Convert.ToDouble(byteHex[iBegin + 5]) / 60 + Convert.ToDouble((byteHex[iBegin + 6] * 256 + byteHex[iBegin + 7])) / 3600000 + AmateParam.Units.dLng;

                    sflag = Convert.ToString(byteHex[iBegin + 8], 2).PadLeft(4, '0');

                    dLat = (Convert.ToInt32(sflag.Substring(0, 2), 2) == 0) ? dLat : -dLat;
                    dLng = (Convert.ToInt32(sflag.Substring(2, 2), 2) == 0) ? dLng : -dLng;
                    if (dLat > 0xFF && dLng > 0xFF) dLat = dLng = 0.0;

                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.S) != null)//速度
                    {
                        sM = new string[1];
                        double dSpeed = (Convert.ToDouble(byteHex[iBegin + 9]) * 256 + Convert.ToDouble(byteHex[iBegin + 10])) * 0.1852;
                        if (dSpeed >= 0 && dSpeed <= 200) sM[0] = dSpeed.ToString();
                        else return dbo.GetMeasureName(AmateParam.Units.S, 1) + dbo.GetLanguage(369) + "(" + dSpeed + dbo.GetMeasureName(AmateParam.Units.S, 2) + ")" + "Error";
                        LsM.Add(sM);
                    }
                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.A) != null)//航向
                    {
                        sM = new string[1];
                        double dCourse = (Convert.ToInt32(byteHex[iBegin + 11]) * 256 + Convert.ToInt32(byteHex[iBegin + 12])) / 10;
                        if (dCourse >= 0 && dCourse < 360) sM[0] = dCourse.ToString();
                        else return dbo.GetMeasureName(AmateParam.Units.A, 1) + dbo.GetLanguage(369) + "(" + dCourse + dbo.GetMeasureName(AmateParam.Units.A, 2) + ")" + "Error";
                        LsM.Add(sM);
                    }
                    iBegin += 13;
                }
                else//定位方式(基站)
                {
                    if (sFlag[5].ToString() == "1")
                    {
                        dLat = byteHex[iBegin] + Convert.ToDouble(byteHex[iBegin + 1]) / 60 + Convert.ToDouble((byteHex[iBegin + 2] * 256 + byteHex[iBegin + 3])) / 3600000 - AmateParam.Units.dLat;
                        dLng = byteHex[iBegin + 4] + Convert.ToDouble(byteHex[iBegin + 5]) / 60 + Convert.ToDouble((byteHex[iBegin + 6] * 256 + byteHex[iBegin + 7])) / 3600000 + AmateParam.Units.dLng;

                        sflag = Convert.ToString(byteHex[iBegin + 8], 2).PadLeft(4, '0');

                        dLat = (Convert.ToInt32(sflag.Substring(0, 2), 2) == 0) ? dLat : -dLat;
                        dLng = (Convert.ToInt32(sflag.Substring(2, 2), 2) == 0) ? dLng : -dLng;
                        if (dLat > 0xFF && dLng > 0xFF) dLat = dLng = 0.0;
                    }
                    else
                    {
                        CellIDString cid = new CellIDString();
                        cid.lac = (Convert.ToInt32(byteHex[iBegin + 5]) * 256 + Convert.ToInt32(byteHex[iBegin + 6])).ToString();
                        cid.cellid = (Convert.ToInt32(byteHex[iBegin + 7]) * 256 + Convert.ToInt32(byteHex[iBegin + 8])).ToString();

                        if (LocateAPI.locate_GoogleMapAPI(cid, out dLat, out dLng))
                        {
                        }
                        else if (LocateAPI.locate_JuHeAPI(cid, out dLat, out dLng))
                        {
                        }
                        if (dLat > 0xFF && dLng > 0xFF) dLat = dLng = 0.0;
                        else
                        {
                            dLat -= AmateParam.Units.dLat;
                            dLng += AmateParam.Units.dLng;
                        }
                    }

                    sM = new string[1];
                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.S) != null)//速度
                        LsM.Add(sM);
                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.A) != null)//航向
                        LsM.Add(sM);
                    iBegin += 9;
                }
            }
            else
            {
                sM = new string[1];
                if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.S) != null)//速度
                    LsM.Add(sM);
                if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.A) != null)//航向
                    LsM.Add(sM);
            }
            if (sFlag[6].ToString() == "1")//电池电量
            {
                if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.B) != null)
                {
                    sM = new string[1];

                    sflag = Convert.ToString(byteHex[iBegin], 2).PadLeft(8, '0');
                    int iBattery = Convert.ToInt32(sflag.Substring(1, 7), 2);
                    if (sflag[0].ToString() == "1") //外部电源
                    {
                        iBattery = -iBattery;
                    }
                    else
                    {
                    }
                    if (iBattery >= -100 && iBattery <= 100) sM[0] = iBattery.ToString();
                    else return dbo.GetMeasureName(AmateParam.Units.B, 1) + dbo.GetLanguage(369) + "(" + iBattery + dbo.GetMeasureName(AmateParam.Units.B, 2) + ")" + "Error";
                    LsM.Add(sM);
                }
                iBegin += 1;
            }

            if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.Sa) != null)
            {
                sM = new string[1];
                sflag = Convert.ToString(byteHex[iBegin], 2).PadLeft(8, '0');
                sM[0] = (Convert.ToInt32(sflag.Substring(0, 4), 2) * 6).ToString();
                LsM.Add(sM);
                if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.Sl) != null)
                {
                    sM = new string[1];
                    sM[0] = Convert.ToInt32(sflag.Substring(4, 4), 2).ToString();
                    LsM.Add(sM);
                    //sSQL = "update SensorXY set LastSl =" + sSatellite + "where ReceiverId=" + iReceiverId;
                }
            }
            iBegin += 1;

            string sExistflag = Convert.ToString(byteHex[iBegin], 2).PadLeft(8, '0'); iBegin += 1;//传感器种类
            int iLen = byteHex[iBegin]; iBegin += 1;//传感器个数
            //if (iLen < 2) return dbo.GetLanguage(440);
            //int iTLen = 0;
            //int iHLen = 0;
            //int iSbLen = 0;
            //DataRow dr = dbo.dtMeasureType.Rows.Find(AmateParam.Units.T);
            //if (dr != null) int.TryParse(dr["Cnum"].ToString(), out iTLen);
            //dr = dbo.dtMeasureType.Rows.Find(AmateParam.Units.H);
            //if (dr != null) int.TryParse(dr["Cnum"].ToString(), out iHLen);
            //dr = dbo.dtMeasureType.Rows.Find(AmateParam.Units.Sb);
            //if (dr != null) int.TryParse(dr["Cnum"].ToString(), out iSbLen);            
            //sM = new string[iTLen + iHLen + iSbLen + 1];
            //if (sM.Length < iLen) iLen = sM.Length;

            for (int iIndex = 0; iIndex < iLen; iIndex++)
            {
                if (iBegin + 2 >= byteHex.Length) break;

                string sDataT = "null";
                string sDataH = "null";
                string sBattery = "null";
                string sSignal = "null";

                int ID = byteHex[iBegin]; iBegin += 1;

                string sExistflagn = Convert.ToString(byteHex[iBegin], 2).PadLeft(8, '0'); iBegin += 1;//传感器种类
                string sAlarmflagn = Convert.ToString(byteHex[iBegin], 2).PadLeft(8, '0'); iBegin += 1;//信号及电量
                if (sExistflag[4].ToString() == "1")
                {
                    if (sExistflagn[4].ToString() == "1")//油量
                    {
                        if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.FL) != null && sExistflag[4].ToString() == "1")
                        {
                            sM[iIndex] = byteHex[iBegin].ToString();
                        }
                        iBegin += 1;
                    }
                    //if (iIndex == 0) iIndex++;
                }
                if (sExistflag[5].ToString() == "1")
                {
                    if (sExistflagn[5].ToString() == "1")//开门量
                    {
                        if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.D) != null && sExistflag[5].ToString() == "1")
                        {
                            int ilen = iIndex;
                            if (ilen <= sM.Length)
                                sM[ilen] = byteHex[iBegin].ToString();
                        }
                        iBegin += 1;
                    }
                    //if (iIndex == 0) iIndex++;
                }

                if (sExistflagn[7].ToString() == "1" || sExistflagn[6].ToString() == "1")
                {
                    if (Convert.ToInt32(sExistflagn, 2) != 0)//dbo.dtMeasureType.Rows.Find(AmateParam.Units.Sb) != null &&
                    {
                        sBattery = Convert.ToInt32(sAlarmflagn.Substring(4, 2), 2).ToString();
                        sSignal = Convert.ToInt32(sAlarmflagn.Substring(6, 2), 2).ToString();

                        //int ilen = ID + iTLen + iTLen - 1;
                        //if (ilen <= sM.Length)
                        //    sM[ilen] = Convert.ToInt32(sAlarmflagn.Substring(3, 1), 2).ToString();
                    }
                }

                if (sExistflagn[6].ToString() == "1")//湿度
                {
                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.H) != null && sExistflag[6].ToString() == "1")
                    {
                        double dData = 0.0;
                        Int32 iData = 0;
                        Int16 item = 0;
                        iData = Convert.ToInt32(byteHex[iBegin]) * 256 + Convert.ToInt32(byteHex[iBegin + 1]);
                        item = Convert.ToInt16(string.Format("{0:x}", iData), 16);
                        dData = ((double)item) / 10.0;

                        if (dData <= 100 && dData > 0)
                        {
                            sDataH = dData.ToString("0.0");
                        }
                    }
                    iBegin += 2;
                }

                if (sExistflagn[7].ToString() == "1")//温度
                {
                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.T) != null && sExistflag[7].ToString() == "1")
                    {
                        double dData = -51.0;
                        Int32 iData = 0;
                        Int16 item = 0;

                        iData = Convert.ToInt32(byteHex[iBegin]) * 256 + Convert.ToInt32(byteHex[iBegin + 1]);
                        item = Convert.ToInt16(string.Format("{0:x}", iData), 16);
                        dData = ((double)item) / 8.0;

                        if (dData < 100 && dData > -100)
                        {
                            sDataT = dData.ToString("0.0");
                        }
                    }
                    iBegin += 2;
                }
                if (sDataT == sDataH && sDataT == "null") continue;
                if (myReceiver.IsExistData(sGPS_Date, ID)) continue;

                if (sbGatherData != null)
                    sbGatherData.AppendFormat(
                        @"Insert into Sys_GatherData(ReceiverId,SensorId,GatherDate,GatherNo,PARA_1,PARA_2,B,S,Lat,Lng) values({0},{1},'{2}','{3}',{4},{5},{6},{7},'{8}','{9}');",
                        myReceiver.sReceiverKeyID, ID, sGPS_Date, sGatherNo, sDataT, sDataH, sBattery, sSignal, dLat,
                        dLng);
                if (sbMapData != null) sbMapData.AppendFormat(@"Update Sys_Map set GatherDate='{2}',PARA_1={4},PARA_2={5},B={6},S={7},State='D1' where ReceiverId={0} and SensorId={1};",
                               myReceiver.sReceiverKeyID, ID, sGPS_Date, sGatherNo, sDataT, sDataH, sBattery, sSignal);
            }

            return sRet;
        }

        /// <summary>
        /// 解析6A01
        /// V5.0
        /// </summary>
        /// <param name="psIP"></param>
        /// <param name="byteHex"></param>
        /// <param name="iReceiverId"></param>
        /// <param name="iBegin"></param>
        /// <param name="LSQL1"></param>
        /// <param name="LSQL2"></param>
        /// <returns></returns>
        private string GatherData_GPS_50(string sIP, byte[] byteHex, MyReceiver myReceiver, int iBegin, ref StringBuilder sbGatherData, ref StringBuilder sbMapData)
        {
            string sFlag, sflag, sRet = "";

            string sGatherDate = PublicFunc.GetUniformDateString(DateTime.Now);
            if (sGatherNo == "" || !blDataFromCall) sGatherNo = sGatherDate;// return "未采集数据!";

            //int iSetClick = 0;
            //int iBegin = 12;
            double dLat = 0.0;
            double dLng = 0.0;
            string[] sM = null;
            List<string[]> LsM = new List<string[]>();

            int iAddrMode = byteHex[iBegin - 6];//地址模式

            sFlag = Convert.ToString(byteHex[iBegin - 5], 2).PadLeft(8, '0');//标识位

            if (sFlag[1].ToString() == "1")//时间格式1
            {
                if (!GetGatherDate(byteHex, ref iBegin, ref sGatherNo, 8)) return dbo.GetLanguage(491) + dbo.GetLanguage(369) + "(" + sGatherNo + ")";// +"Error";
            }
            else sGatherNo = sGatherDate;

            //if (myReceiver.IsExistData(sGPS_Date)) return dbo.GetLanguage(128);//已存在相同数据

            if (sFlag[4].ToString() == "1")//定位信息
            {
                if (sFlag[5].ToString() == "1")//定位方式(精准)
                {
                    dLat = BitConverter.ToSingle(new byte[] { byteHex[iBegin], byteHex[iBegin + 1], byteHex[iBegin + 2], byteHex[iBegin + 3] }, 0) - AmateParam.Units.dLat; ;
                    dLng = BitConverter.ToSingle(new byte[] { byteHex[iBegin + 4], byteHex[iBegin + 5], byteHex[iBegin + 6], byteHex[iBegin + 7] }, 0) + AmateParam.Units.dLng;

                    sflag = Convert.ToString(byteHex[iBegin + 8], 2).PadLeft(4, '0');

                    dLat = (Convert.ToInt32(sflag.Substring(0, 2), 2) == 0) ? dLat : -dLat;
                    dLng = (Convert.ToInt32(sflag.Substring(2, 2), 2) == 0) ? dLng : -dLng;
                    if (dLat > 0xFF && dLng > 0xFF) dLat = dLng = 0.0;

                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.S) != null)//速度
                    {
                        sM = new string[1];
                        double dSpeed = (Convert.ToDouble(byteHex[iBegin + 9]) * 256 + Convert.ToDouble(byteHex[iBegin + 10])) * 0.1852;
                        if (dSpeed >= 0 && dSpeed <= 200) sM[0] = dSpeed.ToString();
                        else return dbo.GetMeasureName(AmateParam.Units.S, 1) + dbo.GetLanguage(369) + "(" + dSpeed + dbo.GetMeasureName(AmateParam.Units.S, 2) + ")" + "Error";
                        LsM.Add(sM);
                    }
                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.A) != null)//航向
                    {
                        sM = new string[1];
                        double dCourse = (Convert.ToInt32(byteHex[iBegin + 11]) * 256 + Convert.ToInt32(byteHex[iBegin + 12])) / 10;
                        if (dCourse >= 0 && dCourse < 360) sM[0] = dCourse.ToString();
                        else return dbo.GetMeasureName(AmateParam.Units.A, 1) + dbo.GetLanguage(369) + "(" + dCourse + dbo.GetMeasureName(AmateParam.Units.A, 2) + ")" + "Error";
                        LsM.Add(sM);
                    }
                    iBegin += 13;
                }
                else//定位方式(基站)
                {
                    dLat = BitConverter.ToSingle(new byte[] { byteHex[iBegin], byteHex[iBegin + 1], byteHex[iBegin + 2], byteHex[iBegin + 3] }, 0) - AmateParam.Units.dLat; ;
                    dLng = BitConverter.ToSingle(new byte[] { byteHex[iBegin + 4], byteHex[iBegin + 5], byteHex[iBegin + 6], byteHex[iBegin + 7] }, 0) + AmateParam.Units.dLng;

                    sflag = Convert.ToString(byteHex[iBegin + 8], 2).PadLeft(4, '0');

                    dLat = (Convert.ToInt32(sflag.Substring(0, 2), 2) == 0) ? dLat : -dLat;
                    dLng = (Convert.ToInt32(sflag.Substring(2, 2), 2) == 0) ? dLng : -dLng;
                    if (dLat > 0xFF && dLng > 0xFF) dLat = dLng = 0.0;

                    sM = new string[1];
                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.S) != null)//速度
                        LsM.Add(sM);
                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.A) != null)//航向
                        LsM.Add(sM);
                    iBegin += 9;
                }
            }
            else
            {
                sM = new string[1];
                if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.S) != null)//速度
                    LsM.Add(sM);
                if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.A) != null)//航向
                    LsM.Add(sM);
            }
            if (sFlag[6].ToString() == "1")//电池电量
            {
                if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.B) != null)
                {
                    sM = new string[1];

                    sflag = Convert.ToString(byteHex[iBegin], 2).PadLeft(8, '0');
                    int iBattery = Convert.ToInt32(sflag.Substring(1, 7), 2);
                    if (sflag[0].ToString() == "1") //外部电源
                    {
                        iBattery = -iBattery;
                    }
                    else
                    {
                    }
                    if (iBattery >= -100 && iBattery <= 100) sM[0] = iBattery.ToString();
                    else return dbo.GetMeasureName(AmateParam.Units.B, 1) + dbo.GetLanguage(369) + "(" + iBattery + dbo.GetMeasureName(AmateParam.Units.B, 2) + ")" + "Error";
                    LsM.Add(sM);
                }
                iBegin += 1;
            }

            if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.Sa) != null)
            {
                sM = new string[1];
                sflag = Convert.ToString(byteHex[iBegin], 2).PadLeft(8, '0');
                sM[0] = (Convert.ToInt32(sflag.Substring(0, 4), 2) * 6).ToString();
                LsM.Add(sM);
                if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.Sl) != null)
                {
                    sM = new string[1];
                    sM[0] = Convert.ToInt32(sflag.Substring(4, 4), 2).ToString();
                    LsM.Add(sM);
                    //sSQL = "update SensorXY set LastSl =" + sSatellite + "where ReceiverId=" + iReceiverId;
                }
            }
            iBegin += 1;

            string sExistflag = Convert.ToString(BitConverter.ToUInt16(new byte[] { byteHex[iBegin], byteHex[iBegin + 1] }, 0), 2).PadLeft(8, '0'); iBegin += 2;//传感器种类
            int iLen = byteHex[iBegin]; iBegin += 1;//传感器个数

            for (int iIndex = 0; iIndex < iLen; iIndex++)
            {
                if (iBegin + 2 >= byteHex.Length) break;

                string sDataT = "null";
                string sDataH = "null";
                string sBattery = "null";
                string sSignal = "null";
                string sSensorTime = sGatherNo;

                int iSensorId = GetSensorID(byteHex, ref iBegin, iAddrMode);

                //if (iAddrMode == 0x00)
                //{
                //    ID = BitConverter.ToInt32(new byte[] { byteHex[iBegin], byteHex[iBegin + 1], byteHex[iBegin + 2], byteHex[iBegin + 3] }, 0);
                //    iBegin += 4;
                //}
                //else if (iAddrMode == 0x10)
                //{
                //    ID = byteHex[iBegin];
                //    iBegin += 1;
                //}

                if (iSensorId > 0 && sFlag[2].ToString() == "1") GetGatherDate(byteHex, ref iBegin, ref sSensorTime, PublicFunc.dTz_cs);

                string sExistflagn = Convert.ToString(BitConverter.ToUInt16(new byte[] { byteHex[iBegin], byteHex[iBegin + 1] }, 0), 2).PadLeft(8, '0'); iBegin += 2;//传感器种类
                string sAlarmflagn = Convert.ToString(byteHex[iBegin], 2).PadLeft(8, '0'); iBegin += 1;//信号及电量
                if (sExistflag[4].ToString() == "1")
                {
                    if (sExistflagn[4].ToString() == "1")//油量
                    {
                        if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.FL) != null && sExistflag[4].ToString() == "1")
                        {
                            sM[iIndex] = byteHex[iBegin].ToString();
                        }
                        iBegin += 1;
                    }
                    //if (iIndex == 0) iIndex++;
                }
                if (sExistflag[5].ToString() == "1")
                {
                    if (sExistflagn[5].ToString() == "1")//开门量
                    {
                        if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.D) != null && sExistflag[5].ToString() == "1")
                        {
                            int ilen = iIndex;
                            if (ilen <= sM.Length)
                                sM[ilen] = byteHex[iBegin].ToString();
                        }
                        iBegin += 1;
                    }
                    //if (iIndex == 0) iIndex++;
                }

                if (sExistflagn[7].ToString() == "1" || sExistflagn[6].ToString() == "1")
                {
                    if (Convert.ToInt32(sExistflagn, 2) != 0)//dbo.dtMeasureType.Rows.Find(AmateParam.Units.Sb) != null &&
                    {
                        sBattery = Convert.ToInt32(sAlarmflagn.Substring(4, 2), 2).ToString();
                        sSignal = Convert.ToInt32(sAlarmflagn.Substring(6, 2), 2).ToString();

                        //int ilen = ID + iTLen + iTLen - 1;
                        //if (ilen <= sM.Length)
                        //    sM[ilen] = Convert.ToInt32(sAlarmflagn.Substring(3, 1), 2).ToString();
                    }
                }

                if (sExistflagn[6].ToString() == "1")//湿度
                {
                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.H) != null && sExistflag[6].ToString() == "1")
                    {
                        double dData = 0.0;
                        Int32 iData = 0;
                        Int16 item = 0;
                        iData = Convert.ToInt32(byteHex[iBegin]) * 256 + Convert.ToInt32(byteHex[iBegin + 1]);
                        item = Convert.ToInt16(string.Format("{0:x}", iData), 16);
                        dData = ((double)item) / 10.0;

                        if (dData < 100 && dData > 0)
                        {
                            sDataH = dData.ToString("0.0");
                        }
                    }
                    iBegin += 2;
                }

                if (sExistflagn[7].ToString() == "1")//温度
                {
                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.T) != null && sExistflag[7].ToString() == "1")
                    {
                        double dData = -51.0;
                        Int32 iData = 0;
                        Int16 item = 0;

                        iData = Convert.ToInt32(byteHex[iBegin]) * 256 + Convert.ToInt32(byteHex[iBegin + 1]);
                        item = Convert.ToInt16(string.Format("{0:x}", iData), 16);
                        dData = ((double)item) / 8.0;

                        if (dData < 100 && dData > -100)
                        {
                            sDataT = dData.ToString("0.0");
                        }
                    }
                    iBegin += 2;
                }
                if (sDataT == sDataH && sDataT == "null") continue;
                if (myReceiver.IsExistData(sGatherNo, iSensorId)) continue;

                if (sbGatherData != null)
                    sbGatherData.AppendFormat(
                        @"Insert into Sys_GatherData(ReceiverId,SensorId,GatherDate,GatherNo,PARA_1,PARA_2,B,S,Lat,Lng) values({0},{1},'{2}','{3}',{4},{5},{6},{7},'{8}','{9}');",
                        myReceiver.sReceiverKeyID, iSensorId, sSensorTime, sGatherNo, sDataT, sDataH, sBattery, sSignal,
                        dLat, dLng);
                if (sbMapData != null) sbMapData.AppendFormat(@"Update Sys_Map set GatherDate='{2}',PARA_1={4},PARA_2={5},B={6},S={7},State='D1' where ReceiverId={0} and SensorId={1};",
                               myReceiver.sReceiverKeyID, iSensorId, sSensorTime, sGatherNo, sDataT, sDataH, sBattery, sSignal);
            }

            return sRet;
        }

        /// <summary>
        /// 解析6A01
        /// V6.0
        /// </summary>
        /// <param name="psIP"></param>
        /// <param name="byteHex"></param>
        /// <param name="iReceiverId"></param>
        /// <param name="iBegin"></param>
        /// <param name="LSQL1"></param>
        /// <param name="LSQL2"></param>
        /// <returns></returns>
        private string GatherData_GPS_60(string sIP, byte[] byteHex, MyReceiver myReceiver, int iBegin, ref StringBuilder sbGatherData, ref StringBuilder sbMapData)
        {
            string sFlag, sflag, sRet = "";

            string sGatherDate = PublicFunc.GetUniformDateString(DateTime.Now);
            if (sGatherNo == "" || !blDataFromCall) sGatherNo = sGatherDate;// return "未采集数据!";

            //int iSetClick = 0;
            //int iBegin = 12;
            double dLat = 0.0;
            double dLng = 0.0;
            string[] sM = null;
            List<string[]> LsM = new List<string[]>();

            int startindex = (iBegin == 12) ? 6 : 2;//判断是否携带地址

            int iAddrMode = byteHex[iBegin - startindex];//地址模式

            sFlag = Convert.ToString(byteHex[iBegin - (startindex - 1)], 2).PadLeft(8, '0');//标识位

            if (sFlag[1].ToString() == "1")//时间格式1
            {
                if (!GetGatherDate(byteHex, ref iBegin, ref sGatherNo, 8)) return dbo.GetLanguage(491) + dbo.GetLanguage(103) + "(" + sGatherNo + ")" + "TimeError";
            }
            else sGatherNo = sGatherDate;

            //if (myReceiver.IsExistData(sGPS_Date)) return dbo.GetLanguage(128);//已存在相同数据

            if (sFlag[4].ToString() == "1")//定位信息
            {
                if (sFlag[5].ToString() == "1")//定位方式(精准)
                {
                    dLat = BitConverter.ToSingle(new byte[] { byteHex[iBegin], byteHex[iBegin + 1], byteHex[iBegin + 2], byteHex[iBegin + 3] }, 0) - AmateParam.Units.dLat; 
                    dLng = BitConverter.ToSingle(new byte[] { byteHex[iBegin + 4], byteHex[iBegin + 5], byteHex[iBegin + 6], byteHex[iBegin + 7] }, 0) + AmateParam.Units.dLng;

                    sflag = Convert.ToString(byteHex[iBegin + 8], 2).PadLeft(4, '0');

                    dLat = (Convert.ToInt32(sflag.Substring(0, 2), 2) == 0) ? dLat : -dLat;
                    dLng = (Convert.ToInt32(sflag.Substring(2, 2), 2) == 0) ? dLng : -dLng;
                    if (dLat > 0xFF && dLng > 0xFF) dLat = dLng = 0.0;

                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.S) != null)//速度
                    {
                        sM = new string[1];
                        double dSpeed = (Convert.ToDouble(byteHex[iBegin + 9]) * 256 + Convert.ToDouble(byteHex[iBegin + 10])) / 10;// *0.1852;
                        if (dSpeed >= 0 && dSpeed <= 200) sM[0] = dSpeed.ToString();
                        else return dbo.GetMeasureName(AmateParam.Units.S, 1) + dbo.GetLanguage(369) + "(" + dSpeed + dbo.GetMeasureName(AmateParam.Units.S, 2) + ")" + "Error";
                        LsM.Add(sM);
                    }
                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.A) != null)//航向
                    {
                        sM = new string[1];
                        double dCourse = BitConverter.ToInt16(new byte[] { byteHex[iBegin + 11], byteHex[iBegin + 12] }, 0) / 10;
                        if (dCourse >= 0 && dCourse < 360) sM[0] = dCourse.ToString();
                        else return dbo.GetMeasureName(AmateParam.Units.A, 1) + dbo.GetLanguage(369) + "(" + dCourse + dbo.GetMeasureName(AmateParam.Units.A, 2) + ")" + "Error";
                        LsM.Add(sM);
                    }
                    iBegin += 13;
                }
                else//定位方式(基站)
                {
                    dLat = BitConverter.ToSingle(new byte[] { byteHex[iBegin], byteHex[iBegin + 1], byteHex[iBegin + 2], byteHex[iBegin + 3] }, 0) - AmateParam.Units.dLat; ;
                    dLng = BitConverter.ToSingle(new byte[] { byteHex[iBegin + 4], byteHex[iBegin + 5], byteHex[iBegin + 6], byteHex[iBegin + 7] }, 0) + AmateParam.Units.dLng;

                    sflag = Convert.ToString(byteHex[iBegin + 8], 2).PadLeft(4, '0');

                    dLat = (Convert.ToInt32(sflag.Substring(0, 2), 2) == 0) ? dLat : -dLat;
                    dLng = (Convert.ToInt32(sflag.Substring(2, 2), 2) == 0) ? dLng : -dLng;
                    if (dLat > 0xFF && dLng > 0xFF) dLat = dLng = 0.0;

                    sM = new string[1];
                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.S) != null)//速度
                        LsM.Add(sM);
                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.A) != null)//航向
                        LsM.Add(sM);
                    iBegin += 9;
                }
            }
            else
            {
                sM = new string[1];
                if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.S) != null)//速度
                    LsM.Add(sM);
                if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.A) != null)//航向
                    LsM.Add(sM);
            }
            if (sFlag[6].ToString() == "1")//电池电量
            {
                if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.B) != null)
                {
                    sM = new string[1];

                    sflag = Convert.ToString(byteHex[iBegin], 2).PadLeft(8, '0');
                    int iBattery = Convert.ToInt32(sflag.Substring(1, 7), 2);
                    if (sflag[0].ToString() == "1") //外部电源
                    {
                        iBattery = -iBattery;
                    }
                    else
                    {
                    }
                    if (iBattery >= -100 && iBattery <= 100) sM[0] = iBattery.ToString();
                    else return dbo.GetMeasureName(AmateParam.Units.B, 1) + dbo.GetLanguage(369) + "(" + iBattery + dbo.GetMeasureName(AmateParam.Units.B, 2) + ")" + "Error";
                    LsM.Add(sM);
                }
                iBegin += 1;
            }

            if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.Sa) != null)
            {
                sM = new string[1];
                sflag = Convert.ToString(byteHex[iBegin], 2).PadLeft(8, '0');
                sM[0] = (Convert.ToInt32(sflag.Substring(0, 4), 2) * 6).ToString();
                LsM.Add(sM);
                if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.Sl) != null)
                {
                    sM = new string[1];
                    sM[0] = Convert.ToInt32(sflag.Substring(4, 4), 2).ToString();
                    LsM.Add(sM);
                    //sSQL = "update SensorXY set LastSl =" + sSatellite + "where ReceiverId=" + iReceiverId;
                }
            }
            iBegin += 1;

            //string sExistflag = Convert.ToString(BitConverter.ToUInt16(new byte[] { byteHex[iBegin], byteHex[iBegin + 1] }, 0), 2).PadLeft(8, '0'); iBegin += 2;//传感器种类
            //增加电能数据
            string sExistflag = Convert.ToString(BitConverter.ToUInt16(new byte[] { byteHex[iBegin], byteHex[iBegin + 1] }, 0), 2).PadLeft(16, '0'); iBegin += 2;//传感器种类

            int iLen = byteHex[iBegin]; iBegin += 1;//传感器个数

            string dlData = string.Empty;
            //含有电能数据
            if (sExistflag[0].ToString() == "1")
            {
                //取电能量
                iBegin += 7;

                dlData =
                    Convert.ToString(
                        BitConverter.ToInt32(
                            new byte[]
                                {byteHex[iBegin], byteHex[iBegin + 1], byteHex[iBegin + 2], byteHex[iBegin + 3]}, 0) *
                        1.0 /
                        800);

                iBegin += 4;

                //传感器个数-1
                iLen = iLen - 1;
            }

            for (int iIndex = 0; iIndex < iLen; iIndex++)
            {
                if (iBegin + 2 >= byteHex.Length) break;

                string sDataT = "null";
                string sDataH = "null";
                string sBattery = "null";
                string sSignal = "null";
                string sSensorTime = sGatherNo;

                int iSensorId = GetSensorID(byteHex, ref iBegin, iAddrMode);

                //if (iAddrMode == 0x00)
                //{
                //    ID = BitConverter.ToInt32(new byte[] { byteHex[iBegin], byteHex[iBegin + 1], byteHex[iBegin + 2], byteHex[iBegin + 3] }, 0);
                //    iBegin += 4;
                //}
                //else if (iAddrMode == 0x10)
                //{
                //    ID = byteHex[iBegin];
                //    iBegin += 1;
                //}

                if (iSensorId > 0 && sFlag[2].ToString() == "1") GetGatherDate(byteHex, ref iBegin, ref sSensorTime, PublicFunc.dTz_cs);

                string sExistflagn = Convert.ToString(BitConverter.ToUInt16(new byte[] { byteHex[iBegin], byteHex[iBegin + 1] }, 0), 2).PadLeft(8, '0'); iBegin += 2;//传感器种类
                string sAlarmflagn = Convert.ToString(byteHex[iBegin], 2).PadLeft(8, '0'); iBegin += 1;//信号及电量
                if (sExistflag[4+8].ToString() == "1")
                {
                    if (sExistflagn[4].ToString() == "1")//油量
                    {
                        if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.FL) != null && sExistflag[4+8].ToString() == "1")
                        {
                            sM[iIndex] = byteHex[iBegin].ToString();
                        }
                        iBegin += 1;
                    }
                    //if (iIndex == 0) iIndex++;
                }
                if (sExistflag[5+8].ToString() == "1")
                {
                    if (sExistflagn[5].ToString() == "1")//开门量
                    {
                        if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.D) != null && sExistflag[5+8].ToString() == "1")
                        {
                            int ilen = iIndex;
                            if (ilen <= sM.Length)
                                sM[ilen] = byteHex[iBegin].ToString();
                        }
                        iBegin += 1;
                    }
                    //if (iIndex == 0) iIndex++;
                }

                if (sExistflagn[7].ToString() == "1" || sExistflagn[6].ToString() == "1")
                {
                    if (Convert.ToInt32(sExistflagn, 2) != 0)//dbo.dtMeasureType.Rows.Find(AmateParam.Units.Sb) != null &&
                    {
                        sBattery = Convert.ToInt32(sAlarmflagn.Substring(4, 2), 2).ToString();
                        sSignal = Convert.ToInt32(sAlarmflagn.Substring(6, 2), 2).ToString();

                        //int ilen = ID + iTLen + iTLen - 1;
                        //if (ilen <= sM.Length)
                        //    sM[ilen] = Convert.ToInt32(sAlarmflagn.Substring(3, 1), 2).ToString();
                    }
                }

                if (sExistflagn[6].ToString() == "1")//湿度
                {
                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.H) != null && sExistflag[6+8].ToString() == "1")
                    {
                        //double dData = 0.0;
                        //Int32 iData = 0;
                        Int16 item = BitConverter.ToInt16(new byte[] { byteHex[iBegin], byteHex[iBegin + 1] }, 0);
                        double dData = ((double)item) / 10.0;

                        if (dData < 100 && dData > 0)
                        {
                            sDataH = dData.ToString("0.0");
                        }
                    }
                    iBegin += 2;
                }

                if (sExistflagn[7].ToString() == "1")//温度
                {
                    if (dbo.dtMeasureType.Rows.Find(AmateParam.Units.T) != null && sExistflag[7+8].ToString() == "1")
                    {
                        double dData = -51.0;
                        //Int32 iData = 0;
                        Int16 item = 0;

                        item = BitConverter.ToInt16(new byte[] { byteHex[iBegin], byteHex[iBegin + 1] }, 0); //Convert.ToInt32(byteHex[iBegin]) * 256 + Convert.ToInt32(byteHex[iBegin + 1]);
                        //item = Convert.ToInt16(string.Format("{0:x}", iData), 16);
                        dData = ((double)item) / 8.0;

                        if (dData < 100 && dData > -100)
                        {
                            sDataT = dData.ToString("0.0");
                        }
                    }
                    iBegin += 2;
                }
                if (sDataT == sDataH && sDataT == "null") continue;
                if (myReceiver.IsExistData(sGatherNo, iSensorId)) continue;

                if (sbGatherData != null)
                    sbGatherData.AppendFormat(
                        @"Insert into Sys_GatherData(ReceiverId,SensorId,GatherDate,GatherNo,PARA_1,PARA_2,B,S,Lat,Lng,ElecEnergy) values({0},{1},'{2}','{3}',{4},{5},{6},{7},'{8}','{9}','{10}');",
                        myReceiver.sReceiverKeyID, iSensorId, sSensorTime, sGatherNo, sDataT, sDataH, sBattery, sSignal,
                        dLat.ToString(), dLng.ToString(), dlData);
                if (sbMapData != null) sbMapData.AppendFormat(@"Update Sys_Map set GatherDate='{2}',PARA_1={4},PARA_2={5},B={6},S={7},State='D1' where ReceiverId={0} and SensorId={1};",
                               myReceiver.sReceiverKeyID, iSensorId, sSensorTime, sGatherNo, sDataT, sDataH, sBattery, sSignal);
            }

            return sRet;
        }

        #region 6.2协议新增即时发送注册命令

        private void AddOrder(MyReceiver dr, string sFlag, string[] sValues, string sOrderName, string sIp)
        {
            string sOrder = "";

            string sReceiverKeyId = dr.iReceiverKeyID.ToString();
            byte[] byteHex = GetOrder(sOrderName, sReceiverKeyId, sFlag, sValues, ref sOrder);

            if (byteHex == null) return;
            sOrder = sOrder.Trim();
            if (sIp != "")
            {
                netSend(sIp, byteHex);
            }

            AmateBussiness.ToLog("SentOrder " + DateTime.Now.ToString("yyyy-MM-dd"), PublicFunc.GetUniformDateString(DateTime.Now), sIp + ":" + sReceiverKeyId);
            AmateBussiness.ToLog("SentOrder " + DateTime.Now.ToString("yyyy-MM-dd"), PublicFunc.GetUniformDateString(DateTime.Now), byteHex);
        }

        #endregion

    }
}
